package com.lancoo.znbkxx.teacher.diagnosis

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.view.View
import androidx.core.content.res.ResourcesCompat
import androidx.lifecycle.ViewModelProvider
import com.github.mikephil.charting.charts.BarChart
import com.github.mikephil.charting.components.MarkerView
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.data.BarData
import com.github.mikephil.charting.data.BarDataSet
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.github.mikephil.charting.highlight.Highlight
import com.lancoo.znbkxx.teacher.Ext
import com.lancoo.znbkxx.teacher.R
import com.lancoo.znbkxx.teacher.aibkTestCoach.aibkTools.MyToast
import com.lancoo.znbkxx.teacher.base.BaseFragment
import com.lancoo.znbkxx.teacher.model.data.CognitiveAbility
import com.lancoo.znbkxx.teacher.model.data.SkillConclusion
import com.lancoo.znbkxx.teacher.net.BkApiMethods
import com.lancoo.znbkxx.teacher.utils.LancooUtils
import com.lancoo.znbkxx.teacher.viewmodel.PaperViewModel
import kotlinx.android.synthetic.main.fragment_language.*
import kotlinx.android.synthetic.main.item_achievement_markview.view.*
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.util.concurrent.TimeoutException

/**
 * @author : Admin
 * @date   : 2020/12/9
 * @desc   :
 */
class LanguageCognitionFragment : BaseFragment() {
    private val skillExcellent = mutableListOf<BarEntry>()
    private val skillTotal = mutableListOf<BarEntry>()
    private val skillPersonal = mutableListOf<BarEntry>()
    private val efficiencyExcellent = mutableListOf<BarEntry>()
    private val efficiencyTotal = mutableListOf<BarEntry>()
    private val efficiencyPersonal = mutableListOf<BarEntry>()
    private val xLabels = mutableListOf<String>()
    private lateinit var viewModel: PaperViewModel
    override fun createLayout(): Int {
        return R.layout.fragment_language
    }

    override fun initView(view: View?) {
        viewModel = ViewModelProvider(requireActivity()).get(PaperViewModel::class.java)
        lifecycle.addObserver(viewModel)
        btn_language.setOnClickListener {
            startActivity(Intent(requireContext(), LanguageTrailActivity::class.java).apply {
                putExtra("stuID", viewModel.StuID.value)
            })
        }
        getLanguageOutputs()
    }

    @SuppressLint("CheckResult")
    fun getLanguageOutputs() {
        val method = BkApiMethods(requireContext())
        val params = BkApiMethods.Paramas()
        params["StuID"] = viewModel.StuID.value
        method.getLanguageOutputs(Ext.RZZD_URL, params).subscribe({
            if (it.Code == 1) {
                initHint(it.Data.SkillConclusion)
                if (it.Data.CognitiveAbility.isEmpty() && it.Data.LearningEfficiency.isEmpty()) {
                    rl_empty_c.visibility = View.VISIBLE
                    btn_language.visibility = View.GONE
                } else {
                    rl_empty_c.visibility = View.GONE
                    btn_language.visibility = View.VISIBLE
                    if (it.Data.CognitiveAbility.isEmpty()) {
                        rl_empty_a.visibility = View.VISIBLE
                    } else {
                        rl_empty_a.visibility = View.GONE
                        initSkillBarChart(
                            bc_language_skill, 0, it.Data.CognitiveAbility
                        )
                    }
                    if (it.Data.LearningEfficiency.isEmpty()) {
                        rl_empty_b.visibility = View.VISIBLE
                    } else {
                        rl_empty_b.visibility = View.GONE
                        initSkillBarChart(
                            bc_language_efficiency, 1, it.Data.LearningEfficiency
                        )
                    }
                }
            } else {
                MyToast.showToast(it.Message)
            }
        }, {
            val error: String =
                if (it is TimeoutException || it is SocketTimeoutException || it is ConnectException) {
                    getString(R.string.aibk_network_timeout)
                } else {
                    getString(R.string.aibk_server_sick)
                }
            MyToast.showToast(error)
        })
    }

    private fun initHint(data: SkillConclusion) {
        when (data.ZH) {
            0 -> iv_icon.setImageResource(R.mipmap.aibk_icon_language_no)
            1 -> iv_icon.setImageResource(R.mipmap.aibk_icon_language_c)
            2 -> iv_icon.setImageResource(R.mipmap.aibk_icon_language_b)
            3 -> iv_icon.setImageResource(R.mipmap.aibk_icon_language_a)
        }
        if (data.ZHText.isNotEmpty()) {
            tv_child.text = data.ZHText
            tv_sub.text = data.OtherText
        } else if (data.OtherText.isNotEmpty()) {
            tv_child.text = data.OtherText
            tv_sub.text = data.NoneText
        } else {
            tv_child.text = data.NoneText
            tv_sub.text = ""
        }
    }


    private fun initSkillBarChart(barChart: BarChart, type: Int, dataList: List<CognitiveAbility>) {
        if (type == 0) {
            skillExcellent.clear()
            skillTotal.clear()
            skillPersonal.clear()
        } else {
            efficiencyExcellent.clear()
            efficiencyTotal.clear()
            efficiencyPersonal.clear()
        }
        xLabels.clear()
        val groupSpace = 0.61f
        val barSpace = 0.03f
        val barWidth = 0.1f
        dataList.forEachIndexed { index, cognitiveAbility ->
            val barEntryExcellent = BarEntry(
                index.toFloat(),
                if (type == 0) cognitiveAbility.ExcellentSkillScore.toFloat() else cognitiveAbility.ExcellentEfficiency.toFloat()
            )
            val barEntryTotal = BarEntry(
                index.toFloat(),
                if (type == 0) cognitiveAbility.TotalSkillScore.toFloat() else cognitiveAbility.TotalEfficiency.toFloat()
            )
            val barEntryPersonal = BarEntry(
                index.toFloat(),
                if (type == 0) cognitiveAbility.PerSkillScore.toFloat() else cognitiveAbility.PerEfficiency.toFloat()
            )
            if (barEntryPersonal.y < barEntryTotal.y) {
                barEntryPersonal.icon = ResourcesCompat.getDrawable(
                    resources,
                    R.mipmap.aibk_1v1_icon_differ, null
                )
            }
            if (type == 0) {
                if (cognitiveAbility.ExcellentSkillScore == 0.0 && cognitiveAbility.TotalSkillScore == 0.0 && cognitiveAbility.PerSkillScore == 0.0) {
                    barEntryTotal.icon = ResourcesCompat.getDrawable(
                        resources,
                        R.mipmap.aibk_icon_low,
                        null
                    )
                }
            } else {
                if (cognitiveAbility.ExcellentEfficiency == 0.0 && cognitiveAbility.TotalEfficiency == 0.0 && cognitiveAbility.PerEfficiency == 0.0) {
                    barEntryTotal.icon = ResourcesCompat.getDrawable(
                        resources,
                        R.mipmap.aibk_icon_low,
                        null
                    )
                }
            }
            if (type == 0) {
                skillExcellent.add(barEntryExcellent)
                skillTotal.add(barEntryTotal)
                skillPersonal.add(barEntryPersonal)
            } else {
                efficiencyExcellent.add(barEntryExcellent)
                efficiencyTotal.add(barEntryTotal)
                efficiencyPersonal.add(barEntryPersonal)
            }
            val name = when (cognitiveAbility.SkillName) {
                "ZH" -> "综合"
                "TL" -> "听力"
                "KY" -> "口语"
                "YD" -> "阅读"
                else -> "写作"
            }
            xLabels.add(name)
        }
        barChart.apply {
            val barDataSetExcellent = BarDataSet(
                if (type == 0) skillExcellent else efficiencyExcellent, "excellent"
            )
            barDataSetExcellent.isHighlightEnabled = false
            barDataSetExcellent.color = Color.parseColor("#22d7bb")
            val barDataSetTotal = BarDataSet(
                if (type == 0) skillTotal else efficiencyTotal,
                "total"
            )
            barDataSetTotal.color = Color.parseColor("#ffd234")
            val barDataSetPersonal = BarDataSet(
                if (type == 0) skillPersonal else efficiencyPersonal, "personal"
            )
            barDataSetPersonal.isHighlightEnabled = false
            barDataSetPersonal.color = Color.parseColor("#2dbcff")
            barDataSetPersonal.setDrawIcons(true)
            val barData = BarData(barDataSetExcellent, barDataSetTotal, barDataSetPersonal)
            barData.setDrawValues(false) //是否显示柱子的数值
            barData.barWidth = barWidth //每个柱子的宽度
            data = barData
            setFitBars(true)
            axisLeft.apply {
                spaceBottom = 0f
                axisMinimum = 0f
                axisMaximum = 105f
                textColor = Color.parseColor("#999999")
            }
            axisRight.isEnabled = false
            //关闭图例
            legend.isEnabled = false
            //关闭描述信息的显示
            description.isEnabled = false
            setScaleEnabled(false)
            //设置x轴显示在下方
            xAxis.apply {
                axisMinimum = 0f
                axisMaximum = dataList.size.toFloat()
                position = XAxis.XAxisPosition.BOTTOM
                isGranularityEnabled = true
                granularity = 1f
                labelCount = xLabels.size
                setCenterAxisLabels(true)
                //设置X轴文本旋转角度
                labelRotationAngle = 0f
                setDrawAxisLine(false)
                setDrawGridLines(false)
                //设置X轴文本大小
                textSize = 11f
                textColor = Color.parseColor("#999999")
                valueFormatter = IndexAxisValueFormatter(xLabels) //设置x轴标签格式化器
            }
            val markerView = MyMarkView(requireContext(), R.layout.item_achievement_markview, type)
            markerView.chartView = this
            marker = markerView
            barChart.groupBars(0f, groupSpace, barSpace)
            animateXY(1000, 1000)
        }
    }

    inner class MyMarkView(context: Context, layoutResource: Int, val type: Int) :
        MarkerView(context, layoutResource) {
        @SuppressLint("SetTextI18n")
        override fun refreshContent(e: Entry?, highlight: Highlight?) {
            val position = when {
                e!!.x < 1f -> 0
                e.x < 2f -> 1
                e.x < 3f -> 2
                e.x < 4f -> 3
                else -> 4
            }
            tv_hint.text =
                "优秀学生：${if (type == 0) skillExcellent[position].y else efficiencyExcellent[position].y}\n" +
                        "整体学生：${if (type == 0) skillTotal[position].y else efficiencyTotal[position].y}\n" +
                        "学生个人：${if (type == 0) skillPersonal[position].y else efficiencyPersonal[position].y}"
            super.refreshContent(e, highlight)
        }
    }
}